<template>
    <!-- pages/generalize/index.wxml -->
    <view class="pages">
        <view class="box">
            <swiper
                @change="swiperChange"
                class="swiper"
                :indicator-dots="indicatorDots"
                :autoplay="autoplay"
                :interval="interval"
                :duration="duration"
                indicator-active-color="#FF8722"
                previous-margin="65rpx"
                next-margin="65rpx"
                :current="current"
            >
                <block v-for="(item, index) in bannerlist" :key="index">
                    <swiper-item class="swiperitem">
                        <image class="swiperimg" :src="item.img" :data-item="item" @tap="previewImg"></image>
                    </swiper-item>
                </block>
            </swiper>
            <view class="canvasbox">
                <canvas
                    width="750"
                    height="1330"
                    style="width: 750px; height: 1330px"
                    type="2d"
                    class="canvas"
                    :canvas-id="'shareCanvas' + index"
                    :id="'shareCanvas' + index"
                    v-for="(item, index) in [0, 1, 2, 3, 4, 5]"
                    :key="index"
                ></canvas>
                <canvas width="750" height="1330" style="width: 750px; height: 1330px" type="2d" class="canvas" canvas-id="shareqr" id="shareqr"></canvas>
            </view>
        </view>
        <view class="flexbox">
            <view class="btn" @tap="onSharePoster">分享海报</view>
            <button open-type="share">
                <view class="btn">分享链接</view>
            </button>
            <view class="btn" @tap="onShareQR">二维码分享</view>
        </view>

        <van-overlay :show="showoMarker" @click="onMarkerHide" :z-index="9999">
            <view class="oreder-wrapper">
                <view class="oreder-wrapperbox" @tap.stop.prevent="shop">
                    <image v-if="makerObj.ismaker" class="oreder-bg" :src="imgUrl + 'isMarkerbg.png'"></image>
                    <image v-if="!makerObj.ismaker" class="oreder-bg" :src="imgUrl + 'noMarkerbg.png'"></image>
                    <button open-type="share" class="oreder-btn">
                        <view>
                            <image class="oreder-btn" :src="imgUrl + 'sharebtn.png'"></image>
                        </view>
                    </button>

                    <view class="oreder-icon" @tap.stop.prevent="onMarkerHide">
                        <van-icon name="close" size="60rpx" color="white" />
                    </view>
                </view>
            </view>
        </van-overlay>
    </view>
</template>

<script>
// pages/generalize/index.js
const app = getApp(); // 引入app

import _request from '../../utils/request.js';
export default {
    data() {
        return {
            invitecode: '',
            imgUrl: app.globalData.imgUrl,

            //全局img路径
            // imglist: [{
            //     img: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/applets/playbill/user_1.jpeg'
            //   },
            //   {
            //     img: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/applets/playbill/user_2.jpeg'
            //   },
            //   {
            //     img: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/applets/playbill/hairdresser_1.jpeg'
            //   },
            //   {
            //     img: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/applets/playbill/hairdresser_2.jpeg'
            //   },
            //   {
            //     img: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/applets/playbill/store_1.jpeg'
            //   },
            //   {
            //     img: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/applets/playbill/store_2.jpeg'
            //   },
            // ],
            imglist: [
                {
                    img: 'https://yiyueuser.oss-cn-shenzhen.aliyuncs.com/1498200738097319938.png'
                },
                {
                    img: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/images/user_3.png'
                },
                {
                    img: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/images/hairdresser_3.png'
                },
                {
                    img: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/images/store_3.png'
                }
            ],

            indicatorDots: false,
            vertical: false,
            autoplay: false,
            duration: 500,
            margin55: '',
            codeimg: '',
            showimg: '',
            bannerlist: '',

            // 合成后图片路径
            makerObj: null,

            showoMarker: false,
            current: 0,
            shareQr: '',

            //二维码分享
            //分享码背景图
            shareImage: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/images/share_qr.png',

            data1: '',
            interval: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        uni.getSystemInfo({
            success: (res) => {
                this.setData({
                    data1: res
                });
            }
        });

        if (options.invitecode) {
            uni.setStorageSync('code', options.invitecode);
        } // 获取邀请码

        _request
            .get('/recomUser/findReCode', {
                userId: uni.getStorageSync('userid')
            })
            .then((res) => {
                this.setData({
                    invitecode: res.data.data.invitecode
                }); // 获取邀请二维码

                _request
                    .get('/basicSetting/getWXShareQrCode', {
                        referralCode: this.invitecode,
                        userId: uni.getStorageSync('userid')
                    })
                    .then((res) => {
                        this.setData({
                            codeimg: res.data.data
                        }); // 绘制背景海报到canvas

                        const { imglist, codeimg, bannerlist } = this;
                        let list = [];
                        imglist.map((item, index) => {
                            this.drawPoster1(item.img, this.codeimg, index).then((res) => {
                                list.push(res);
                                this.sort(list);
                                this.setData(
                                    {
                                        bannerlist: list,
                                        showimg: list[0].img
                                    },
                                    () => {
                                        this.setData({
                                            current: options.index ? Number(options.index) : 0
                                        });
                                    }
                                );
                            });
                        });
                        this.drawShareQR(this.codeimg);
                    })
                    .catch((error) => {
                        console.log(error, 'error');
                    });
            })
            .catch((error) => {
                console.log(error, 'error');
            });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 是否创客
        _request
            .get('/maker/checkIsMaker', {
                userId: uni.getStorageSync('userid')
            })
            .then((res) => {
                let vm = this;
                vm.setData({
                    makerObj: res.data.data
                });
            });
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (res) {
        // 设置菜单中的转发按钮触发转发事件时的转发内容
        if (res.from === 'button') {
            // 来自页面内转发按钮
        }

        console.log('firstpages/home/index?invitecode=' + this.invitecode);
        let title = '好友邀请您上意约小程序领520大礼包！';
        return {
            title: title,
            // 默认是小程序的名称
            path: 'firstpages/home/index?invitecode=' + this.invitecode,
            success: function (res) {},
            imageUrl: 'https://kjyiyue.oss-cn-shenzhen.aliyuncs.com/images/saker.png'
        };
    },
    methods: {
        // 点击关闭
        onMarkerHide() {
            this.setData({
                showoMarker: false
            });
        },

        // 轮播事件
        swiperChange(e) {
            let index = e.detail.current;
            this.setData({
                showimg: this.bannerlist[index].img
            });
        },

        //点击图片进行预览，长按保存分享图片
        previewImg(e) {
            this.setData({
                showimg: e.currentTarget.dataset.item.img
            });
            let list = this.bannerlist.map((item) => {
                return item.img;
            });
            uni.previewImage({
                current: e.currentTarget.dataset.item.img,
                // 当前显示图片的http链接
                urls: list // 需要预览的图片http链接列表
            });
        },

        // 分享海报
        onSharePoster() {
            let list = this.bannerlist.map((item) => {
                return item.img;
            });
            uni.previewImage({
                current: this.showimg,
                // 当前显示图片的http链接
                urls: list // 需要预览的图片http链接列表
            });
        },

        //二维码分享
        onShareQR() {
            uni.previewImage({
                urls: this.shareQr // 需要预览的图片http链接列表
            });
        },

        // 合成海报
        // drawPoster(circleBg, qrCodeUrl) {
        //   circleBg.map((item, index) => {
        //     let id = 'shareCanvas' + index
        //     let posterCanvas = wx.createSelectorQuery().select('#' + id)
        //     return new Promise((resolve, reject) => {
        //       posterCanvas.fields({
        //         node: true,
        //         size: true
        //       }).exec(res => {
        //         const canvas = res[0].node
        //         const ctx = canvas.getContext('2d')
        //         const dpr = wx.getSystemInfoSync().pixelRatio
        //         canvas.width = res[0].width * dpr
        //         canvas.height = res[0].height * dpr
        //         // 绘制海报
        //         wx.getImageInfo({
        //           src: item.img,
        //           success: res => {
        //             let imageUrl = res.path // 图片临时地址
        //             let imageW = res.width
        //             let imageH = res.height
        //             let ratio = imageW / canvas.width // 获取比例
        //             let imageObj = canvas.createImage()
        //             imageObj.src = imageUrl
        //             imageObj.onload = (res) => {
        //               ctx.drawImage(imageObj, 0, 0, imageW / ratio, imageH / ratio);
        //               // 绘制二维码
        //               wx.getImageInfo({
        //                 src: qrCodeUrl,
        //                 success: res => {
        //                   let qrImageUrl = res.path
        //                   let qrImageW = 180 // 二维码大小
        //                   let qrRatio = ratio
        //                   let qrImageObj = canvas.createImage()
        //                   qrImageObj.src = qrImageUrl
        //                   qrImageObj.onload = (res) => {
        //                     // 图片,left,top,width,height
        //                     ctx.drawImage(qrImageObj, 50, canvas.height - (qrImageW + 100) / qrRatio, qrImageW / qrRatio, qrImageW / qrRatio)
        //                     // canvas转图片临时路径
        //                     wx.canvasToTempFilePath({
        //                       canvas: canvas,
        //                       fileType: 'png',
        //                       success: res => {
        //                         resolve(res)
        //                         this.setData({
        //                           bannerlist: [...this.data.bannerlist, {
        //                             'img': res.tempFilePath,
        //                             'id': index
        //                           }],
        //                         })
        //                         this.setData({
        //                           showimg: this.data.bannerlist[0].img
        //                         })
        //                       },
        //                       fail: err => {
        //                         reject(err)
        //                       }
        //                     })
        //                   }
        //                 },
        //                 fail: err => {
        //                   reject(err)
        //                 },
        //               })
        //             }
        //           },
        //           fail: err => {
        //             reject(err)
        //           },
        //         })
        //       })
        //     })
        //   })
        // },
        drawPoster1(circleBg, qrCodeUrl, index) {
            let id = 'shareCanvas' + index;
            let posterCanvas = uni.createSelectorQuery().select('#' + id);
            return new Promise((resolve, reject) => {
                posterCanvas
                    .fields({
                        node: true,
                        size: true
                    })
                    .exec((res) => {
                        const canvas = res[0].node;
                        const ctx = canvas.getContext('2d');
                        const dpr = uni.getSystemInfoSync().windowWidth / 375;
                        canvas.width = res[0].width * dpr;
                        canvas.height = res[0].height * dpr; // 绘制海报

                        uni.getImageInfo({
                            src: circleBg,
                            success: (res) => {
                                let imageUrl = res.path; // 图片临时地址

                                let imageW = res.width / dpr;
                                let imageH = res.height / dpr;
                                let ratio = imageW / canvas.width; // 获取比例

                                let imageObj = canvas.createImage();
                                imageObj.src = imageUrl;

                                imageObj.onload = (res) => {
                                    ctx.drawImage(imageObj, 0, 0, imageW / ratio, imageH / ratio); // 绘制二维码

                                    uni.getImageInfo({
                                        src: qrCodeUrl,
                                        success: (res) => {
                                            let qrImageUrl = res.path;
                                            let qrImageW = 150 / dpr; // 二维码大小

                                            let qrRatio = ratio;
                                            let qrImageObj = canvas.createImage();
                                            qrImageObj.src = qrImageUrl;

                                            qrImageObj.onload = (res) => {
                                                const info = uni.getSystemInfoSync();

                                                if (index == 0) {
                                                    ctx.drawImage(
                                                        qrImageObj,
                                                        canvas.width / 2 - (qrImageW + 120) / qrRatio / 2,
                                                        canvas.height - (qrImageW + 200) / qrRatio,
                                                        (qrImageW + 120) / qrRatio,
                                                        (qrImageW + 120) / qrRatio
                                                    );
                                                } else {
                                                    ctx.drawImage(
                                                        qrImageObj,
                                                        canvas.width - (qrImageW + 90) / qrRatio,
                                                        canvas.height - (qrImageW + 90) / qrRatio,
                                                        qrImageW / qrRatio,
                                                        qrImageW / qrRatio
                                                    );
                                                } // canvas转图片临时路径

                                                uni.canvasToTempFilePath({
                                                    canvas: canvas,
                                                    fileType: 'png',
                                                    success: (res) => {
                                                        let data = {
                                                            img: res.tempFilePath,
                                                            id: index
                                                        };
                                                        resolve(data);
                                                    },
                                                    fail: (err) => {
                                                        reject(err);
                                                    }
                                                });
                                            };
                                        },
                                        fail: (err) => {
                                            reject(err);
                                        }
                                    });
                                };
                            },
                            fail: (err) => {
                                reject(err);
                            }
                        });
                    });
            });
        },

        // 数组排序
        sort(arr) {
            for (var j = 0; j < arr.length - 1; j++) {
                //两两比较，如果前一个比后一个大，则交换位置。
                for (var i = 0; i < arr.length - 1 - j; i++) {
                    if (arr[i].id > arr[i + 1].id) {
                        var temp = arr[i];
                        arr[i] = arr[i + 1];
                        arr[i + 1] = temp;
                    }
                }
            }
        },

        //绘制分享码
        drawShareQR(qrCodeUrl) {
            let posterCanvas = uni.createSelectorQuery().select('#shareqr');
            const nickName = uni.getStorageSync('nickName') || '';
            return new Promise((resolve, reject) => {
                posterCanvas
                    .fields({
                        node: true,
                        size: true
                    })
                    .exec((res) => {
                        const canvas = res[0].node;
                        const ctx = canvas.getContext('2d');
                        const dpr = uni.getSystemInfoSync().windowWidth / 375;
                        canvas.width = res[0].width * dpr;
                        canvas.height = res[0].height * dpr; // 绘制海报

                        uni.getImageInfo({
                            src: this.shareImage,
                            success: (res) => {
                                let imageUrl = res.path; // 图片临时地址

                                let imageW = res.width / dpr;
                                let imageH = res.height / dpr;
                                let ratio = imageW / canvas.width; // 获取比例

                                let imageObj = canvas.createImage();
                                imageObj.src = imageUrl;

                                imageObj.onload = (res) => {
                                    ctx.drawImage(imageObj, 0, 100 / dpr / ratio, imageW / ratio, imageH / ratio); // 绘制二维码

                                    uni.getImageInfo({
                                        src: qrCodeUrl,
                                        success: (res) => {
                                            let qrImageUrl = res.path;
                                            let qrImageW = 420 / dpr; // 二维码大小

                                            let qrRatio = ratio;
                                            let qrImageObj = canvas.createImage();
                                            qrImageObj.src = qrImageUrl;

                                            qrImageObj.onload = (res) => {
                                                ctx.drawImage(
                                                    qrImageObj,
                                                    (canvas.width - (qrImageW + 0) / qrRatio) / 2,
                                                    canvas.height - (qrImageW + 540 / dpr) / qrRatio,
                                                    qrImageW / qrRatio,
                                                    qrImageW / qrRatio
                                                );
                                                ctx.font = '36px'; //字体大小

                                                ctx.fillStyle = '#666'; //字体颜色

                                                ctx.textAlign = 'center'; //文字居中
                                                // ctx.fillText(nickName, (canvas.width - ctx.measureText(nickName).width/dpr/qrRatio/4)/2, 400/dpr/qrRatio)

                                                ctx.fillText(nickName, canvas.width / 2, 400 / dpr / qrRatio);
                                                ctx.fillStyle = '#fff'; //字体颜色

                                                ctx.fillText(this.invitecode, canvas.width / 2, 720 / dpr / qrRatio); // canvas转图片临时路径

                                                uni.canvasToTempFilePath({
                                                    canvas: canvas,
                                                    fileType: 'jpg',
                                                    quality: 1,
                                                    success: (res) => {
                                                        this.setData({
                                                            shareQr: [res.tempFilePath]
                                                        });
                                                    },
                                                    fail: (err) => {
                                                        console.log('----2----', err);
                                                    }
                                                });
                                            };
                                        },
                                        fail: (err) => {
                                            console.log('----3----', err);
                                        }
                                    });
                                };

                                imageObj.onerror = (res) => {
                                    console.log('----4----', res);
                                };
                            },
                            fail: (err) => {
                                console.log('----5----', err);
                            }
                        });
                    });
            });
        },

        shop() {
            console.log('占位：函数 shop 未声明');
        }
    }
};
</script>
<style>
/* pages/generalize/index.wxss */
/* 轮播 */
button {
    font: inherit !important;
    margin: 0 !important;
    padding: 0 !important;
    background: none !important;
    line-height: unset !important;
    text-align: inherit !important;
    width: unset !important;
    color: inherit !important;
    position: initial !important;
    box-sizing: inherit !important;
    border: unset !important;
    min-height: unset !important;
    display: block !important;
}

button::after {
    display: none;
}

.pages {
    box-sizing: border-box;
    padding-top: 60rpx;
    overflow: hidden;
}

.box {
    display: block;
    overflow: hidden;
    height: 968rpx;
    box-sizing: border-box;
}

.swiper {
    width: 100%;
    height: 100%;
}

.swiperimg {
    width: 560rpx;
    height: 968rpx;
    -o-object-fit: cover;
    object-fit: cover;
}

.swiperitem {
    padding: 0 40rpx;
    box-sizing: border-box;
}

.btn {
    /* height: 48rpx; */
    background: #ff8722;
    box-shadow: 0px 2px 4px 0px rgba(255, 128, 0, 0.26);
    border-radius: 24rpx;
    text-align: center;
    color: white;
    font-size: 28rpx;
    /* line-height: 48rpx; */
    float: right;
    padding: 10rpx 26rpx;
    box-sizing: border-box;
}

.flexbox {
    display: flex;
    flex-wrap: nowrap;
    justify-content: space-around;
    margin-top: 50rpx;
    padding: 0 100rpx;
}

.codeimg {
    width: 200rpx;
    height: 200rpx;
    position: absolute;
}

.canvas {
    height: 1330rpx;
    width: 750rpx;
}

.canvasbox {
    width: 5000rpx;
    float: left;
    margin-left: 750rpx;
}

.img {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
}

.oreder-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    position: relative;
}

.oreder-wrapperbox {
    width: 640rpx;
    position: absolute;
    /* top: 120rpx; */
    height: 1030rpx;
    display: flex;
    justify-content: center;
    border-radius: 5px;
}

.oreder-btn {
    width: 510rpx;
    height: 112rpx;
    position: absolute;
    bottom: 40rpx;
    left: 66rpx;
}

.oreder-bg {
    width: 640rpx;
    height: 1030rpx;
    position: absolute;
    /* top: 50rpx; */
}

.oreder-icon {
    position: absolute;
    /* bottom: -200rpx; */
    top: -28rpx;
    right: -24rpx;
}
</style>
